<template>
	<view v-if="!firstLoad" class="container">
		<img v-if="!startPreview && liveStatus == -1" class="intro-image" :src="handleImageUrl(data.livePosterSmall)" />
		<template v-else>
			<view class="video-block">				
				<video v-if="startReplay" :enable-progress-gesture="controls" autoplay :loop="loop" id="video" class="video" :src="playUrl"></video>
	
				<video v-if="liveStatus == -1 || liveStatus == 1" :show-progress="false" @play="liveStartPlay" :enable-progress-gesture="false" autoplay :loop="loop" id="video" class="video video1" :src="playUrl"></video>
			</view>

			<view class="video-body">
				<view class="video-title">
					<view class="sub-title">{{data && data.title ? data.title : ''}}</view>
					<!-- <view v-if="stateTag" :class="['tag', startQA ? '' : `tag${liveStatus}`]">{{ stateTag }}</view> -->
				</view>
				<view class="sub-time">播出时间：</view>
				<view>{{ duration }}</view>
				<template v-if="!isPureLive">
					<view class="sub-time">答疑时间：</view>
					<view>{{ qrDuration }}</view>
				</template>
			</view>

		</template>
		<view v-if="startQA && !isPureLive" @click="handleClick" class="bottom-button">开始提问</view>
		<view v-if="tipText && liveStatus == 0 && !startReplay" class="tip">{{ tipText }}</view>
		<Popxzhz ref="popup3"></Popxzhz>
	</view>
</template>

<script>
import { getLiveDetail, refreshLog } from '@/api/index'
import { handleImageUrl, handleAuthVideoUrl } from '@/utils/common'
import hlsjs from 'hls.js'
import { setStudio } from '@/utils/auth9' 
import { setOrganizationId } from '@/utils/auth2' 
import Popxzhz from '@/components/Popxzhz.vue'

export default {
	components:{
		Popxzhz
	},
	data() {
		return {
			id: null,
			data: null,
			liveStatus: -1, // -1: 未开始；1：已开始；0: 已结束
			timer: null,
			firstLoad: true,
			startPreview: false,
			playUrl: '',
			startQA: false, //开始答疑
			loop: true, //循环播放
			tipText: '',
			controls: false,
			startTime: 0,  // 快进
			startReplay: false, // 开始回放
			videoContext: null,
			showButton: false, // 显示提问按钮
			isPureLive: false, // 是否纯直播
		}
	},
	onLoad(params) {
		const id = params?.id
		if (id) this.id = id
		refreshLog('live', id)
	},
	onShow() {
		this.init()
	},
	beforeDestroy() {
		this.beforeRouteLeave()
	},
	methods: {
		beforeRouteLeave () {
			clearInterval(this.timer)
			this.videoContext?.pause()
		},
		handleImageUrl,
		init() {
			getLiveDetail(this.id).then(res => {
				if (res?.code == 200) {
					let { liveDetail, rosteringDetail } = res.data

					this.isPureLive = !Boolean(rosteringDetail)

					this.data = {...liveDetail, ...(rosteringDetail || {})}


					// 直播状态 -1: 未开始；1：已开始；0: 已结束
					this.liveStatus = res.data.liveDetail.liveStatus
					if (this.timer) clearInterval(this.timer)
					this.handleVideoState()
				}
				this.firstLoad = false
			})
		},
		// 处理播放状态
		handleVideoState() {
			// liveType 1: 直播  2：假直播
			const { liveType, startTime, endTime, liveStartSecond, liveShimUrl, liveStartTime, liveEndTime, liveReplayStartTime } = this.data
			const [start, end] = [new Date(startTime?.replace(/-/g,"/")), new Date(endTime?.replace(/-/g,"/"))]
			const time = new Date()
			const liveStatus = this.liveStatus
			clearInterval(this.timer)

			const t = 3
			// 直播未开始
			if (liveStatus == -1) { 
				// 十分钟内播放预告片
				if (liveStartSecond > -60*10) { 
					this.startPreview = true
								
					this.playUrl = handleAuthVideoUrl(liveShimUrl)
					this.startPlay()
					// 答疑状态
					this.startQA = time > start
				}
				this.timer = setInterval(() => {
					this.data.liveStartSecond += t

					if (!this.startQA) this.startQA = new Date() > start

					if (this.data.liveStartSecond > 0) {
						// 直播开始
						this.liveStatus = 1
						clearInterval(this.timer)
						this.startPreview = false
						this.showButton = true
						this.videoContext?.exitFullScreen()
						this.handleVideoState()
					} else if (this.data.liveStartSecond > -60*10 && !this.startPreview) { 
						// console.log(1233)
						// 预告片 -- 直播开始前10分钟开始播放
						this.startPreview = true
		
						this.playUrl = handleAuthVideoUrl(liveShimUrl)
						this.startPlay()
					}
					// console.log('读秒-1', this.data.liveStartSecond, !this.startPreview && this.liveStatus == -1)
				}, t * 1000)
			} else if (liveStatus == 1){
				this.showButton = true
				// console.log('直播开始1')
				this.loop = false
				// 直播中 -- 状态处理

				this.playUrl = handleAuthVideoUrl(this.data.livePlaySmallUrl)
			
				const duration = (new Date(liveEndTime.replace(/-/g,"/")) - new Date(liveStartTime.replace(/-/g,"/"))) / 1000
			
				// console.log('直播时长', duration)
				// 假直播
				if (liveType == 2 && liveStatus==1) { 
					if(this.data.liveStartSecond) this.startTime = this.data.liveStartSecond
				}
				this.startPlay()

				// 答疑状态
				this.startQA = time > start && time < end
				
				this.timer = setInterval(() => {
					this.data.liveStartSecond += t
					// console.log('读秒1', this.data.liveStartSecond)
					const _time = new Date()
					// 答疑状态
					this.startQA = _time > start && _time < end
					// 直播结束
					if (this.liveStatus!=0 && duration - this.data.liveStartSecond <= 0) {
						this.liveStatus = 0
						this.videoContext?.exitFullScreen()
						this.videoContext.pause()
						clearInterval(this.timer)

						this.handleVideoState() // 切换到结束状态timer
					}
				}, t*1000)

			} else {
				// 直播结束 -- 开始回放
				this.tipText = `直播结束啦！`
				if (liveReplayStartTime) {
					this.tipText += `可于${liveReplayStartTime.slice(0,16)}后收看回放呦`
				}

				if (!this.isPureLive && new Date() < end) {
					this.showButton = true
					this.startQA = true
					this.timer = setInterval(() => {
						// console.log('读秒0', this.data.liveStartSecond)
						// 答疑状态
						const _time = new Date()
						this.startQA = _time > start && _time < end
			
						// 答疑结束
						if ( _time > end) {  
							this.startQA = false
							this.showButton = false
							clearInterval(this.timer)
						}
					}, t * 1000)
				}

				if (liveReplayStartTime && new Date() >= new Date(liveReplayStartTime.replace(/-/g,"/"))) {
					this.playUrl = handleAuthVideoUrl(this.data.liveReplaySmallUrl)
					this.controls = true
					this.startQA = false
					this.startReplay = true
					this.startPlay()
				}
			}
			
		},
		// 开始播放
		startPlay() {
			if (!this.playUrl) return;
			
			this.$nextTick(() => {
				const videoPlayer = uni.createVideoContext('video')
				this.videoContext = videoPlayer

				// 视频链接类型
				const reg = /\.(mp4|avi|mov|wmv)/i
				
				// video标签直接播放
				if (reg.test(this.playUrl)) { 
					try {
						videoPlayer?.play()
						if (this.liveStatus ==2 && this.startTime>0) {
							videoPlayer?.seek(this.startTime)
						}
					} catch (error) {
						console.error('video加载失败', error)
					}
				} else if(hlsjs.isSupported()) {
					this.hlsjs = new hlsjs()
					this.hlsjs.loadSource(this.playUrl)  //设置播放路径
					this.hlsjs.attachMedia(videoPlayer)  //解析到video标签上
					this.hlsjs.on(hlsjs.Events.MANIFEST_PARSED, () => {
						try {
							videoPlayer?.play()
							if (this.liveStatus ==2 && this.startTime>0) {
								videoPlayer?.seek(this.startTime)
							}
						} catch (error) {
							console.error('直播加载失败')
						}
					})
				} else {
					uni.showToast({
						title: '不支持的视频格式',
						duration: 2000
					})
				}
			})
		},
		handleClick() {
			// flag : 1 心里排班 0:工作室排班级
			const { flag } = this.data
			if (this.$store.state.user.name) {
				let url = flag == 1 ? '/pages/psychological/startask' : '/pages/aqc/startask'
				if (flag !=1) {
					let data = {
						id: this.data.workroomId,
						isBelongCity: this.data.isBelongCity,
						organizationId: this.data.organizationId,
					};
					setOrganizationId(this.data.organizationId);
					setStudio(data);
				}
				this.beforeRouteLeave()
				this.$store.state.user.urlstartask = this.$route.fullPath
				this.$router.push(url)
			}else{
				this.beforeRouteLeave()
				this.$store.state.user.urllogin = this.$route.fullPath
				this.$tab.reLaunch('/pages/login')
				// this.$refs.popup3.open();
			}
		},
		liveStartPlay() {
			this.videoContext?.seek(this.data.liveStartSecond)
			if(this.liveStatus) {
				refreshLog('livePlay', this.data.id)
			}
		},
	},
	computed: {
		stateTag() {
			const status = ['待开始', '已结束', '直播中']
			let state = this.data ? status[this.liveStatus + 1] : ''

			if (!this.isPureLive && this.liveStatus!=1 && this.startQA) state = '答疑中'

			return state
		},
		duration() {
			let { liveShowStartTime, liveShowEndTime } = this.data
			if(!liveShowStartTime || !liveShowEndTime ) return ''
			return `${liveShowStartTime?.substr(0, 16)} - ${liveShowEndTime?.substr(11, 5)}`
		},
		qrDuration() {
			let { showStartTime, showEndTime } = this.data
			if(!showStartTime || !showEndTime ) return ''
			return `${showStartTime?.substr(0, 16)} - ${showEndTime?.substr(0, 16)}`
		},
	},
}
</script>

<style scoped>
.container {
	position: relative;
}
.video1 ::v-deep .uni-video-progress-container {
	display: none;
}
.video1 ::v-deep .uni-video-current-time {
	display: none;
}
.video1 ::v-deep .uni-video-duration {
	display: none;
}
.intro-image {
	width: 100vw;
}

.video-block {
	width: 100vw;
	height: 56.25vw;
	background: #000;
	position: relative;
}

.full-btn {
	position: absolute;
	right: 0;
	bottom: 0;
	width: 15vw;
	height: 10vw;
	border: 1px solid red;
	z-index: 100;
}

.video {
	width: 100vw;
	height: 56.25vw;
	object-fit: fill;
}

.video-body {
	box-sizing: border-box;
	width: 100vw;
	height: auto;
	padding: 0 3.2vw;
	font-size: 4.8vw;
	color: #333;
}

.video-title {
	display: flex;
	justify-content: space-between;
	flex-wrap: nowrap;
	margin-top: 4vw;
}

.sub-title {
	font-size: 5.33vw;
	font-weight: bold;
	color: #000;
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
}

.tag {
	/* flex: 1; */
	min-width: 16.53vw;
	height: 7.2vw;
	text-align: center;
	line-height: 7.2vw;
	background: #3FECD3;
	border-radius: 2.4vw;
	color: #333;
	font-size: 4.27vw;
	font-weight: normal;
	margin-left: 2vw;
}

.tag0 {
	background: #DDD;
}

.tag-1 {
	background: #FFE46D;
}

.sub-time {
	font-size: 4.8vw;
	line-height: 4.8vw;
	color: #666;
	margin: 3.73vw 0;
}

.bottom-button {
	width: 34.67vw;
	height: 11.73vw;
	background: #1893FF;
	border-radius: 5.87vw;
	text-align: center;
	line-height: 11.73vw;
	color: #fff;
	font-size: 4.27vw;
	position: absolute;
	top: 75vh;
	left: 0;
	right: 0;
	margin: 0 auto;
}

.tip {
	position: absolute;
	top: 40vw;
	width: 100vw;
	text-align: center;
	margin: 0 auto;
	font-size: 4vw;
	color: #fff;
}
</style>
